package com.itheima.excel_demo.service.Impl;

import com.alibaba.excel.EasyExcel;
import com.google.errorprone.annotations.Var;
import com.itheima.excel_demo.controller.ExcelDataListener;
import com.itheima.excel_demo.mapper.ExcelDataMapper;
import com.itheima.excel_demo.service.ExcelService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ExcelServiceImpl implements ExcelService {
    @Override
    public Map<String, Integer> parseExcel(MultipartFile file) {
        List<String> result = new ArrayList<>();

        try {
            EasyExcel.read(file.getInputStream(), ExcelDataMapper.class, new ExcelDataListener(result)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<String> specificationShortNames = extractSpecificationShortName(result);

        Map<String, Integer> specNameCountMap = countSpecificationShortNames(specificationShortNames);


        return specNameCountMap;
    }

    /**
     * 获取所有的specificationShortName
     *
     * @param result
     * @return
     */
    private static List<String> extractSpecificationShortName(List<String> result) {
        List<String> specificationShortNames = new ArrayList<>();
        for (String data : result) {
            int startIndex = data.indexOf("specificationShortName=");
            if (startIndex != -1) {
                int endIndex = data.indexOf(",", startIndex);
                if (endIndex == -1) {
                    endIndex = data.length();
                }
                String specificationShortName = data.substring(startIndex + "specificationShortName=".length(), endIndex).trim();
                if (specificationShortName.endsWith(")")) {
                    specificationShortName = specificationShortName.substring(0, specificationShortName.length() - 1).trim();
                }
                specificationShortNames.add(specificationShortName);
            }
        }
        return specificationShortNames;
    }

    /**
     * 获取所有specificationShortName的重复数据并统计数量
     *
     * @param specificationShortNames
     * @return
     */
    private static Map<String, Integer> countSpecificationShortNames(List<String> specificationShortNames) {
        Map<String, Integer> specNameCountMap = new HashMap<>();
        for (String specName : specificationShortNames) {
            specNameCountMap.put(specName, specNameCountMap.getOrDefault(specName, 0) + 1);
        }
        for (Map.Entry<String, Integer> entry : specNameCountMap.entrySet()) {
            System.out.println("数据为: " + entry.getKey() + " - 数量为: " + entry.getValue() + "个");
        }
        return specNameCountMap;
    }


}
